<!-- AnswerRenderer.vue -->
<template>
  <div class="answer-renderer">
    <!-- 混合类型 -->
    <div v-if="answer?.answer_type === 'mixed'" class="mixed-answer">
      <div v-if="answer.title" class="answer-title">{{ answer.title }}</div>
      <div
        v-if="answer.sections && answer.sections.length > 0"
        class="sections-container"
      >
        <div
          v-for="(section, index) in answer.sections"
          :key="index"
          class="section-item"
          :class="`section-${section.type}`"
        >
          <!-- 文本类型 section -->
          <div v-if="section.type === 'text'" class="section-text">
            <div
              class="section-content"
              v-html="formatSectionText(section.content)"
            ></div>
          </div>

          <!-- 图表类型 section -->
          <div v-else-if="section.type === 'chart'" class="section-chart">
            <div class="chart-placeholder">
              <p v-if="section.title" class="section-title">
                {{ section.title }}
              </p>
              <div
                class="chart-mock"
                :style="{
                  background:
                    section.chart_type === 'pie' ? '#f5fafe' : '#e6f7ff',
                }"
              >
                <span>{{ section.chart_type || "chart" }} 图表</span>
              </div>
            </div>
          </div>

          <!-- 表格类型 section -->
          <div v-else-if="section.type === 'table'" class="section-table">
            <div class="table-placeholder">
              <p v-if="section.title" class="section-title">
                {{ section.title }}
              </p>
              <table v-if="section.columns && section.data" class="data-table">
                <thead>
                  <tr>
                    <th v-for="col in section.columns" :key="col.key || col">
                      {{ col.name || col }}
                    </th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(row, i) in section.data" :key="i">
                    <td v-for="col in section.columns" :key="col.key || col">
                      {{ row[col.key || col] }}
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>

          <!-- 图谱类型 section -->
          <div v-else-if="section.type === 'graph'" class="section-graph">
            <div class="graph-placeholder">
              <p v-if="section.title" class="section-title">
                {{ section.title }}
              </p>
              <div class="graph-mock">
                <span>关联图谱可视化</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 文本类型 -->
    <div v-else-if="answer?.answer_type === 'text'" class="text-answer">
      <div class="text-content" v-html="formatText(answer.content)"></div>
    </div>

    <!-- 图表类型 -->
    <div v-else-if="answer?.answer_type === 'chart'" class="chart-answer">
      <div class="chart-placeholder">
        <p v-if="answer.title" class="chart-title">图表：{{ answer.title }}</p>
        <div
          class="chart-mock"
          :style="{
            background: answer.chart_type === 'pie' ? '#f5fafe' : '#e6f7ff',
          }"
        >
          <!-- 实际应用中应使用 ECharts 或其他图表库 -->
          <span>{{ answer.chart_type || "chart" }} 图表</span>
        </div>
      </div>
    </div>

    <!-- 表格类型 -->
    <div v-else-if="answer?.answer_type === 'table'" class="table-answer">
      <div class="table-placeholder">
        <p v-if="answer.title" class="table-title">表格：{{ answer.title }}</p>
        <table v-if="answer.columns && answer.data" class="data-table">
          <thead>
            <tr>
              <th v-for="col in answer.columns" :key="col.key || col">
                {{ col.name || col }}
              </th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(row, i) in answer.data" :key="i">
              <td v-for="col in answer.columns" :key="col.key || col">
                {{ row[col.key || col] }}
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 图谱类型 -->
    <div v-else-if="answer?.answer_type === 'graph'" class="graph-answer">
      <div class="graph-placeholder">
        <p v-if="answer.title" class="graph-title">
          关联图谱：{{ answer.title }}
        </p>
        <div class="graph-mock">
          <!-- 实际应用中应使用图谱可视化库 -->
          <span>关联图谱可视化</span>
        </div>
      </div>
    </div>

    <!-- 默认：直接显示 content 或整个 answer -->
    <div v-else class="default-answer">
      <div
        v-if="answer?.content"
        class="text-content"
        v-html="formatText(answer.content)"
      ></div>
      <div v-else class="fallback-content">
        <pre>{{ JSON.stringify(answer, null, 2) }}</pre>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed } from "vue";

const props = defineProps({
  answer: {
    type: Object,
    required: true,
    default: () => ({}),
  },
});

// 格式化文本，支持简单的 Markdown 格式
const formatText = (text) => {
  if (!text || typeof text !== "string") {
    return "";
  }

  // 转义 HTML 特殊字符
  let formatted = text
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;");

  // 处理粗体 **text** 或 __text__
  formatted = formatted.replace(/\*\*(.+?)\*\*/g, "<strong>$1</strong>");
  formatted = formatted.replace(/__(.+?)__/g, "<strong>$1</strong>");

  // 处理斜体 *text* 或 _text_
  formatted = formatted.replace(/\*(.+?)\*/g, "<em>$1</em>");
  formatted = formatted.replace(/_(.+?)_/g, "<em>$1</em>");

  // 处理换行
  formatted = formatted.replace(/\n/g, "<br>");

  // 处理代码块 `code`
  formatted = formatted.replace(
    /`([^`]+)`/g,
    '<code class="inline-code">$1</code>'
  );

  return formatted;
};

// 格式化 section 文本，支持结构化内容（如 \n- 格式）
const formatSectionText = (text) => {
  if (!text || typeof text !== "string") {
    return "";
  }

  // 转义 HTML 特殊字符
  let formatted = text
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;");

  // 处理粗体 **text** 或 __text__
  formatted = formatted.replace(/\*\*(.+?)\*\*/g, "<strong>$1</strong>");
  formatted = formatted.replace(/__(.+?)__/g, "<strong>$1</strong>");

  // 处理斜体 *text* 或 _text_
  formatted = formatted.replace(/\*(.+?)\*/g, "<em>$1</em>");
  formatted = formatted.replace(/_(.+?)_/g, "<em>$1</em>");

  // 处理代码块 `code`
  formatted = formatted.replace(
    /`([^`]+)`/g,
    '<code class="inline-code">$1</code>'
  );

  // 处理结构化内容：\n- 开头的行转换为列表项
  // 先处理 \n- 格式，转换为列表
  const lines = formatted.split("\n");
  const processedLines = [];
  let inList = false;

  lines.forEach((line, index) => {
    // 检查是否是列表项（以 - 开头，前面可能有空格）
    const listMatch = line.match(/^(\s*)- (.+)$/);
    if (listMatch) {
      if (!inList) {
        processedLines.push("<ul class='structured-list'>");
        inList = true;
      }
      processedLines.push(
        `<li class='structured-item'><span class='item-label'>${
          listMatch[1] ? "&nbsp;".repeat(listMatch[1].length) : ""
        }</span><span class='item-content'>${listMatch[2]}</span></li>`
      );
    } else {
      if (inList) {
        processedLines.push("</ul>");
        inList = false;
      }
      if (line.trim()) {
        processedLines.push(`<p class='text-paragraph'>${line}</p>`);
      } else {
        processedLines.push("<br>");
      }
    }
  });

  if (inList) {
    processedLines.push("</ul>");
  }

  return processedLines.length > 0
    ? processedLines.join("")
    : formatted.replace(/\n/g, "<br>");
};
</script>

<style scoped lang="scss">
.answer-renderer {
  line-height: 1.6;
  color: #333;
  word-wrap: break-word;
  word-break: break-word;
}

/* 混合类型样式 */
.mixed-answer {
  .answer-title {
    font-size: 16px;
    font-weight: 600;
    color: #333;
    margin-bottom: 16px;
    padding-bottom: 8px;
    border-bottom: 2px solid #667eea;
  }

  .sections-container {
    display: flex;
    flex-direction: column;
    gap: 16px;
  }

  .section-item {
    margin-bottom: 0;
  }

  .section-text {
    .section-content {
      font-size: 14px;
      line-height: 1.8;
      color: #333;

      :deep(.structured-list) {
        list-style: none;
        padding: 0;
        margin: 4px 0;
        display: flex;
        flex-direction: column;
        gap: 12px;
        li {
          padding: 0;
        }
      }

      :deep(.structured-item) {
        padding: 12px 16px;
        background: #f8f9fa;
        border-radius: 8px;
        display: flex;
        align-items: flex-start;
        gap: 8px;
        transition: all 0.2s;
        border: 1px solid #e8e8e8;

        &:hover {
          background: #f0f7ff;
          box-shadow: 0 2px 8px rgba(102, 126, 234, 0.15);
          border-color: #667eea;
        }
      }

      // :deep(.item-label) {
      //   color: #409eff;
      //   font-weight: 600;
      //   flex-shrink: 0;
      //   min-width: 4px;
      // }

      :deep(.item-content) {
        flex: 1;
        color: #333;
        line-height: 1.6;

        strong {
          color: #409eff;
          font-weight: 600;
        }
      }

      :deep(.text-paragraph) {
        margin: 8px 0;
        line-height: 1.8;
        color: #333;
      }

      :deep(strong) {
        font-weight: 600;
        color: #667eea;
      }

      :deep(em) {
        font-style: italic;
        color: #666;
      }

      :deep(.inline-code) {
        background: #f5f5f5;
        padding: 2px 6px;
        border-radius: 3px;
        font-family: "Courier New", monospace;
        font-size: 13px;
        color: #e83e8c;
      }
    }
  }

  .section-title {
    margin: 0 0 12px 0;
    font-weight: 600;
    color: #333;
    font-size: 14px;
  }
}

.text-answer {
  .text-content {
    font-size: 14px;
    line-height: 1.8;
    color: #333;

    :deep(strong) {
      font-weight: 600;
      color: #667eea;
    }

    :deep(em) {
      font-style: italic;
      color: #666;
    }

    :deep(.inline-code) {
      background: #f5f5f5;
      padding: 2px 6px;
      border-radius: 3px;
      font-family: "Courier New", monospace;
      font-size: 13px;
      color: #e83e8c;
    }
  }
}

.chart-placeholder,
.table-placeholder,
.graph-placeholder {
  margin-bottom: 16px;
  padding: 16px;
  border-radius: 8px;
  background: #f9f9f9;
  border: 1px solid #e8e8e8;
}

.chart-title,
.table-title,
.graph-title {
  margin: 0 0 12px 0;
  font-weight: 600;
  color: #333;
  font-size: 14px;
}

.chart-mock,
.graph-mock {
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  color: #666;
  background: #f0f0f0;
  font-size: 14px;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 8px;
  background: #fff;
  border-radius: 4px;
  overflow: hidden;
}

.data-table th,
.data-table td {
  border: 1px solid #e8e8e8;
  padding: 10px 12px;
  text-align: left;
  font-size: 13px;
}

.data-table th {
  background: #f0f0f0;
  font-weight: 600;
  color: #333;
}

.data-table tbody tr:hover {
  background: #f5f5f5;
}

.default-answer {
  .text-content {
    font-size: 14px;
    line-height: 1.8;
    color: #333;

    :deep(strong) {
      font-weight: 600;
      color: #667eea;
    }

    :deep(em) {
      font-style: italic;
      color: #666;
    }

    :deep(.inline-code) {
      background: #f5f5f5;
      padding: 2px 6px;
      border-radius: 3px;
      font-family: "Courier New", monospace;
      font-size: 13px;
      color: #e83e8c;
    }
  }

  .fallback-content {
    pre {
      margin: 0;
      padding: 12px;
      background: #f5f5f5;
      border-radius: 4px;
      font-size: 12px;
      color: #666;
      overflow-x: auto;
      white-space: pre-wrap;
      word-wrap: break-word;
    }
  }
}
</style>
